package com.example.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhoubin
 */
public class ContainerSingleton {

    private ContainerSingleton() {
    }

    private static Map<String, Object> ioc = new ConcurrentHashMap<String, Object>();

    public static Object getInstance(String className) {
        if (!ioc.containsKey(className)) {
            // 这会锁着所有线程
//            synchronized (ContainerSingleton.class) {
            // 这种只会锁着响应key的线程
            synchronized (className) {
                if (ioc.containsKey(className)) {
                    return ioc.get(className);
                }

                Object instance = null;
                try {
                    instance = Class.forName(className).newInstance();
                    ioc.put(className, instance);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return instance;
            }
        } else {
            return ioc.get(className);
        }
    }


    public static void main(String[] args) {
//        Object pojo = ContainerSingleton.getInstance(ContainerPojo.class.getName());
//        System.out.println(pojo);


        new Thread(() -> {
            Object pojo1 = ContainerSingleton.getInstance(ContainerPojo.class.getName());
            System.out.println(Thread.currentThread().getName() + ": " + pojo1);
        }, "Thread-1").start();

        new Thread(() -> {
            Object pojo1 = ContainerSingleton.getInstance(ContainerPojo.class.getName());
            System.out.println(Thread.currentThread().getName() + ": " + pojo1);
        }, "Thread-2").start();

        new Thread(() -> {
            Object entity = ContainerSingleton.getInstance(ContainerEntity.class.getName());
            System.out.println(Thread.currentThread().getName() + ": " + entity);
        }, "Thread-3").start();

        System.out.println("End");


    }

}
